/*
 * 版权所有 (C) 2001-2014 深圳市艾派应用系统有限公司。保留所有权利。
 * 版本：
 * 修改记录：
 *		1、2014-11-25，tfl创建。 
 */
package com.chinamobile.ln.ictenterprises.http;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import android.util.Log;

import com.chinamobile.ln.ictenterprises.common.GlobalSetting;
import com.chinamobile.ln.ictenterprises.model.Step;
import com.chinamobile.ln.ictenterprises.utils.MyLogger;

@SuppressWarnings("deprecation")
public class HttpSend
{
    protected static final MyLogger logger = MyLogger.getLogger();
    private static final HttpClient httpClient = new HttpClient(); // HttpClient对象
    private boolean isActive = true;// 链接状态
    public final static String JSON_REQUEST = "JSON";
    private MultiThreadedHttpConnectionManager connectionManager = null;
    private static HttpSend instance = new HttpSend();

    public static HttpSend getInstance()
    {
        return instance;
    }

    /** 创建单例时构造 */
    private HttpSend()
    {
        connectionManager = new MultiThreadedHttpConnectionManager();
        connectionManager.setMaxTotalConnections(100);
        connectionManager.setMaxConnectionsPerHost(100);
        // 把连接管理放置到httpClient
        httpClient.setConnectionTimeout(60 * 1000);
        httpClient.setTimeout(60 * 1000);
        httpClient.setHttpConnectionManager(connectionManager);
        httpClient.getParams().setParameter("1",
            new DefaultHttpMethodRetryHandler(0, false));
    }

    /**
     * 阻塞式发送请求,并返回响应,注:如果异常,则返回null <br>
     * 
     * @param request 请求
     * @return byte[] 响应
     * @throws Exception
     */
    public static Map<String, Object> send(Step step, String tmpcookies)
    {
        PostMethod postMethod = null;
        RequestEntity entity = null;
        Map<String, Object> retMap = new HashMap<String, Object>();
        int statusCode = 0;
        try
        {
            // 设置 HttpClient 接收 Cookie,用与浏览器一样的策略
            httpClient.getParams().setCookiePolicy(
                CookiePolicy.BROWSER_COMPATIBILITY);
            if (step.getRequestType() != null
                && JSON_REQUEST.equalsIgnoreCase(step.getRequestType()))
            {
                entity = new ByteArrayRequestEntity(step.getStreamString()
                    .getBytes(step.getEncoding()));
                postMethod = new PostMethod(step.getUrl().trim());
                postMethod.setRequestEntity(entity);
                postMethod.setRequestHeader("Referer", step.getUrl().trim());
                // 每次访问需授权的网址时需带上前面的 cookie 作为通行证
                if (tmpcookies != null)
                    postMethod.setRequestHeader("cookie", tmpcookies);
                // 流对象 未处理
                logger.e("发送消息" + step.getUrl().trim() + "请求方式【"
                    + step.getRequestType() + "】");
            }
            else
            {
                logger.e("发送消息" + step.getUrl().trim() + "时无效,原因:无效的请求方式【"
                    + step.getRequestType() + "】");
            }
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            InputStream in = null;
            statusCode = httpClient.executeMethod(postMethod);
            Log.i("HttpSend", "statusCode:" + statusCode);
            retMap.put(GlobalSetting.STUATUS_CODE, statusCode);
            Cookie[] cookies = httpClient.getState().getCookies();
            if (tmpcookies.equals(""))
                for (Cookie c : cookies)
                {
                    tmpcookies += c.toString() + ";";
                }
            Log.i("HttpSend", "tmpcookies:" + tmpcookies);
            retMap.put(GlobalSetting.TMP_COOKIES, tmpcookies);
            in = postMethod.getResponseBodyAsStream();
            int b;
            while ((b = in.read()) != -1)
            {
                out.write((byte) b);
            }
            String retstrString = new String(out.toByteArray(),
                step.getEncoding());
            retMap.put(GlobalSetting.RET_DATA, retstrString);
        }
        catch (Exception e)
        {
            Log.i("HttpSend", e.getMessage());
            retMap.put(GlobalSetting.STUATUS_CODE, statusCode);
            retMap.put(GlobalSetting.RET_DATA, "");
            retMap.put(GlobalSetting.TMP_COOKIES, "");
        }
        finally
        {
            // 释放链接
            if (postMethod != null)
            {
                postMethod.releaseConnection();
            }
        }
        return retMap;
    }

    public boolean isActive()
    {
        return isActive;
    }

    public void setActive(boolean isActive)
    {
        this.isActive = isActive;
    }

}
